package main

import (
	"flag"
	"fmt"
	"github.com/chai2010/winsvc"
	"github.com/go-resty/resty/v2"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

var (
	serviceName = flag.String("service", "php7430-D-portal-9006", "服务名称（注意和显示名称有区别）")
	url         = flag.String("url", "https://www.gxgj.com/", "监听的网址")
	errorStr    = flag.String("err", "An error occurred", "检测的错误触发字符串")
	intv        = flag.Int("intv", 30, "检测周期（秒）")
)

func init() {
	file := "./" + "message" + ".log"
	logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
	if err != nil {
		panic(err)
	}
	log.SetOutput(logFile) // 将文件设置为log输出的文件
	log.SetPrefix("[GXGJ.COM]")
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	return
}
func main() {
	flag.Parse()
	mylog("开始守护")
	mylog("service:" + *serviceName + " url:" + *url + " intv:" + strconv.Itoa(*intv) + " err:" + *errorStr)
	client := resty.New()

	for {
		resp, err := client.R().Get(*url)
		if err != nil {
			mylog(err.Error())
		}
		//fmt.Println("Status Code:", resp.StatusCode())
		str := resp.String()
		if strings.Index(str, *errorStr) == -1 {
			mylog("healthy")
		} else {
			mylog("An error occurred in php, I will restart php service ..")
			mylog("stoping..")
			if err := winsvc.StopService(*serviceName); err != nil {
				mylog("StopService:" + err.Error())
			}
			time.Sleep(3 * time.Second)
			mylog("starting..")
			if err := winsvc.StartService(*serviceName); err != nil {
				mylog("StartService:" + err.Error())
			}
			mylog("StartService " + *serviceName + " Done")
		}

		time.Sleep(time.Duration(*intv) * time.Second)
	}

	return
}

func mylog(str string) {
	timeStr := time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(timeStr + " " + str)
	log.Println(str)
}
